<template>
	<view class="content">
		<!-- 顶部标题栏 -->
		<view class="header">
			<view class="distance-info">
				<text v-if="distance !== null">距离打卡点: {{ distance.toFixed(0) }}米</text>
				<text v-else>计算中...</text>
			</view>
		</view>

		<!-- 地图区域 -->
		<view class="page-section page-section-gap">
			<map id="myMap" style="width: 100%; height: 400px;" :latitude="latitude" :longitude="longitude"
				:markers="markers" show-location @regionchange="onRegionChange"></map>
		</view>

		<!-- 打卡区域 -->
		<view class="punch-section">
			<button class="punch-btn" :class="{ 'active': inRange, 'offline': !isOnline }" @click="handlePunch"
				:disabled="!inRange">
				<text v-if="inRange">
					{{ isOnline ? '立即打卡' : '离线打卡' }}
				</text>
				<text v-else>不在打卡范围内</text>
			</button>
			<!-- 添加网络状态提示 -->
			<view v-if="!isOnline" class="network-tip">
				<text>当前处于离线模式，打卡记录将在网络恢复后自动同步</text>
			</view>
			<view class="location-info">
				<view class="info-item">
					<text class="label">当前位置:</text>
					<text class="value">{{ currentAddress || '定位中...' }}</text>
				</view>
				<view class="info-item">
					<text class="label">打卡地点:</text>
					<text class="value">{{targetLocation.name}}</text>
				</view>
			</view>
		</view>

		<!-- 打卡记录 -->
		<view class="records-section">
			<view class="section-title">
				<text>打卡记录</text>
				<text class="clear-btn" @click="clearRecords">清空</text>
			</view>

			<scroll-view scroll-y="true" class="records-list">
				<view v-if="punchRecords.length === 0" class="empty">
					<text>暂无打卡记录</text>
				</view>

				<view v-for="(record, index) in punchRecords" :key="index" class="record-item">
					<view class="record-time">
						<text>{{ record.time }}</text>
						<text class="record-date">{{ record.date }}</text>
					</view>
					<view class="record-location">
						<text>{{ record.location }}</text>
						<text class="record-distance">距离: {{ record.distance.toFixed(0) }}米</text>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 新增网络状态标识
				isOnline: true,
				// 新增离线记录队列
				offlineRecords: [],
				// 初始位置
				latitude: 0,
				longitude: 0,
				// latitude: 30.320894,
				// longitude: 120.353237,

				// 当前位置
				currentLat: null,
				currentLng: null,
				currentAddress: '',

				// 打卡点位置
				targetLocation: {
					latitude: 30.320894,
					longitude: 120.353237,
					name: '杭州职业技术学院'
				},

				// 距离信息
				distance: null,
				inRange: false,

				// 标记点
				markers: [{
						id: 1,
						latitude: 30.320894,
						longitude: 120.353237,
						name: '打卡点',
						iconPath: '/static/image/sign/target.png',
						width: 30,
						height: 30
					},
					{
						id: 2,
						latitude: 30.320894,
						longitude: 120.353237,
						name: '我的位置',
						iconPath: '/static/image/sign/location.png',
						width: 30,
						height: 30
					}
				],

				// 打卡记录
				punchRecords: []
			}
		},

		computed: {
			// 计算打卡按钮状态
			punchButtonText() {
				return this.inRange ? '立即打卡' : '不在打卡范围内';
			}
		},

		onLoad() {
			this.getAuthorizeInfo();
			this.loadRecords();
			this.checkNetworkStatus();
			// 监听网络状态变化
			uni.onNetworkStatusChange(this.handleNetworkChange);
		},

		onShow() {
			// 每分钟更新一次位置
			this.locationTimer = setInterval(() => {
				this.getLocationInfo();
			}, 60000);
		},

		onHide() {
			clearInterval(this.locationTimer);
		},

		methods: {
			// 新增方法：检查网络状态
			checkNetworkStatus() {
				uni.getNetworkType({
					success: (res) => {
						this.isOnline = res.networkType !== 'none';
						if (!this.isOnline) {
							uni.showToast({
								title: '当前处于离线模式',
								icon: 'none'
							});
						}
					}
				});
			},

			// 新增方法：处理网络状态变化
			handleNetworkChange(res) {
				this.isOnline = res.isConnected;
				if (res.isConnected) {
					// 网络恢复时尝试同步离线记录
					this.syncOfflineRecords();
					uni.showToast({
						title: '网络已恢复',
						icon: 'success'
					});
				} else {
					uni.showToast({
						title: '已进入离线模式',
						icon: 'none'
					});
				}
			},
			// 位置授权
			getAuthorizeInfo() {
				// 动态检测API是否存在
				if (typeof uni.authorize === 'function') {
					uni.authorize({
						scope: 'scope.userLocation',
						success: () => {
							this.getLocationsCheck();
						},
						fail: () => {
							this.openConfirm();
						}
					});
				} else {
					console.warn("当前环境不支持授权");
					this.getLocationsCheck();
					// H5/APP 的替代方案：
					// 1. 普通权限请求
					// 2. 跳转系统设置页
					// 3. 显示引导提示
				}
			},
			// 获取打卡点位
			getLocationsCheck() {
				var check_latitude = this.targetLocation.latitude
				var check_longitude = this.targetLocation.longitude
				console.log(check_latitude, check_longitude);
				uni.openLocation({
					type: 'gcj02',
					geocode: true,
					latitude: check_latitude,
					longitude: check_longitude,
					success: (res) => {
						console.log("=====获取打卡点位====");
						console.log(res);
						const adderss = res.address
						// than.targetLocation.name = adderss.poiName
					},
					complete: () => {
						this.getLocationInfo()
					}
				});
			},

			// 获取地理位置
			getLocationInfo() {
				uni.getLocation({
					type: 'gcj02',
					geocode: true,
					success: (res) => {
						console.log(res);
						this.currentLat = res.latitude;
						this.currentLng = res.longitude;

						// 更新地图中心位置
						this.latitude = res.latitude;
						this.longitude = res.longitude;

						// 更新位置标记
						this.updateMarkers();

						// 获取地址信息
						this.getAddress();
					},
					fail: (err) => {
						console.error('获取位置失败:', err);
						uni.showToast({
							title: '获取位置失败',
							icon: 'none'
						});
					}
				});
			},

			// 获取地址信息
			getAddress() {
				console.log("======获取地址信息=====");
				uni.getLocation({
					type: 'gcj02',
					geocode: true, //设置该参数为true可直接获取经纬度及城市信息
					latitude: this.currentLat,
					longitude: this.currentLng,
					success: (res) => {
						console.log(res);
						const adderss = res.address
						this.currentAddress = adderss.poiName
						this.calculateDistance();
					},
					fail: (error) => {
						console.log("报错：" + error);
					}
				});

			},

			// 更新标记点
			updateMarkers() {
				console.log("=====更新标记点=====");
				this.markers[1] = {
					...this.markers[1],
					latitude: this.currentLat,
					longitude: this.currentLng
				};

				// 强制更新标记点
				this.markers = [...this.markers];
			},

			// 计算距离
			calculateDistance() {
				console.log("=====计算打卡位置====");
				if (!this.currentLat || !this.currentLng) return;

				// 使用Haversine公式计算距离
				const R = 6371000; // 地球半径(米)
				const φ1 = this.currentLat * Math.PI / 180;
				const φ2 = this.targetLocation.latitude * Math.PI / 180;
				const Δφ = (this.targetLocation.latitude - this.currentLat) * Math.PI / 180;
				const Δλ = (this.targetLocation.longitude - this.currentLng) * Math.PI / 180;

				const a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
					Math.cos(φ1) * Math.cos(φ2) *
					Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
				const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

				this.distance = R * c;

				// 判断是否在打卡范围内 (100米内)
				this.inRange = this.distance <= 100;
			},

			// 再次获取授权
			openConfirm() {
				uni.showModal({
					title: '请求授权当前位置',
					content: '需要获取您的地理位置才能使用打卡功能',
					success: (res) => {
						if (res.confirm) {
							uni.openSetting();
						}
					}
				});
			},

			// 地图区域变化
			onRegionChange(e) {
				if (e.type === 'end') {
					// 地图移动结束后重新获取位置
					this.getLocationInfo();
				}
			},
			// 修改后的打卡处理方法
			handlePunch() {
				if (!this.inRange) return;

				// 创建打卡记录
				const now = new Date();
				const record = {
					time: `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`,
					date: `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`,
					location: this.currentAddress || '未知位置',
					distance: this.distance,
					timestamp: now.getTime(),
					synced: this.isOnline // 标记是否已同步
				};

				if (this.isOnline) {
					// 在线模式 - 直接处理
					this.processPunchRecord(record);
				} else {
					// 离线模式 - 存入离线队列
					this.storeOfflineRecord(record);
				}
			},

			// 新增方法：处理打卡记录
			processPunchRecord(record) {
				uni.showLoading({
					title: '打卡中...',
					mask: true
				});

				// 模拟网络请求
				setTimeout(() => {
					this.punchRecords.unshift(record);
					this.saveRecords();

					uni.hideLoading();
					uni.showToast({
						title: '打卡成功',
						icon: 'success'
					});
				}, 1000);
			},

			// 新增方法：存储离线记录
			storeOfflineRecord(record) {
				// 添加到内存队列
				this.offlineRecords.unshift(record);
				// 保存到本地存储
				try {
					uni.setStorageSync('offlinePunchRecords', this.offlineRecords);

					// 同时更新显示记录
					this.punchRecords.unshift(record);
					this.saveRecords();

					uni.showToast({
						title: '离线打卡成功(网络恢复后自动同步)',
						icon: 'success'
					});
				} catch (e) {
					console.error('保存离线记录失败:', e);
					uni.showToast({
						title: '保存离线记录失败',
						icon: 'none'
					});
				}
			},

			// 新增方法：同步离线记录
			syncOfflineRecords() {
				try {
					const records = uni.getStorageSync('offlinePunchRecords');
					if (records && records.length > 0) {
						uni.showLoading({
							title: '同步离线记录中...',
							mask: true
						});

						// 模拟网络请求同步
						setTimeout(() => {
							// 这里应该是实际的上传逻辑
							console.log('正在同步离线记录:', records);

							// 同步成功后清空离线记录
							uni.removeStorageSync('offlinePunchRecords');
							this.offlineRecords = [];

							uni.hideLoading();
							uni.showToast({
								title: `成功同步${records.length}条离线记录`,
								icon: 'success'
							});
						}, 1500);
					}
				} catch (e) {
					console.error('同步离线记录失败:', e);
				}
			},

			// 修改加载记录方法
			loadRecords() {
				try {
					// 加载正常记录
					const records = uni.getStorageSync('punchRecords');
					if (records) {
						this.punchRecords = records;
					}

					// 加载离线记录
					const offlineRecords = uni.getStorageSync('offlinePunchRecords');
					if (offlineRecords) {
						this.offlineRecords = offlineRecords;
					}
				} catch (e) {
					console.error('加载记录失败:', e);
				}
			},
			
			// 保存记录
			saveRecords() {
				try {
					uni.setStorageSync('punchRecords', this.punchRecords);
				} catch (e) {
					console.error('保存打卡记录失败:', e);
				}
			},


			// 清空记录
			clearRecords() {
				uni.showModal({
					title: '确认清空',
					content: '确定要清空所有打卡记录吗？',
					success: (res) => {
						if (res.confirm) {
							this.punchRecords = [];
							uni.removeStorageSync('punchRecords');
						}
					}
				});
			}
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f5f5f5;
	}

	.header {
		padding: 20rpx 30rpx;
		background: linear-gradient(to right, #4b6cb7, #182848);
		color: white;
	}

	.title {
		font-size: 36rpx;
		font-weight: bold;
		text-align: center;
		margin-bottom: 10rpx;
	}

	.distance-info {
		font-size: 28rpx;
		text-align: center;
		color: #FFD700;
	}

	.page-section-gap {
		box-sizing: border-box;
		padding: 0 30rpx;
	}

	.punch-section {
		padding: 20rpx 30rpx;
		background-color: #fff;
		margin: 20rpx 30rpx;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.punch-btn {
		background-color: #4CAF50;
		color: white;
		border-radius: 50rpx;
		font-size: 32rpx;
		height: 80rpx;
		line-height: 80rpx;
		margin-bottom: 30rpx;
		transition: all 0.3s;
	}

	.punch-btn.active {
		background-color: #FF9800;
		box-shadow: 0 4rpx 12rpx rgba(255, 152, 0, 0.3);
	}

	/* 新增离线模式样式 */
	.punch-btn.offline {
		background-color: #FFC107 !important;
	}

	.network-tip {
		font-size: 24rpx;
		color: #FF9800;
		text-align: center;
		margin-bottom: 20rpx;
	}

	.punch-btn[disabled] {
		background-color: #cccccc;
		color: #666666;
	}

	.location-info {
		border-top: 1rpx solid #eeeeee;
		padding-top: 20rpx;
	}

	.info-item {
		display: flex;
		margin-bottom: 15rpx;
	}

	.label {
		width: 150rpx;
		color: #666;
		font-size: 28rpx;
	}

	.value {
		flex: 1;
		font-size: 28rpx;
		color: #333;
	}

	.records-section {
		flex: 1;
		background-color: #fff;
		margin: 0 30rpx 30rpx;
		border-radius: 16rpx;
		padding: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		display: flex;
		flex-direction: column;
	}

	.section-title {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
		padding-bottom: 15rpx;
		border-bottom: 1rpx solid #eeeeee;
	}

	.clear-btn {
		font-size: 26rpx;
		color: #f44336;
	}

	.records-list {
		flex: 1;
	}

	.empty {
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #999;
		font-size: 28rpx;
	}

	.record-item {
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.record-time {
		font-size: 30rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
		display: flex;
		align-items: center;
	}

	.record-date {
		font-size: 24rpx;
		color: #999;
		margin-left: 20rpx;
		font-weight: normal;
	}

	.record-location {
		font-size: 28rpx;
		color: #666;
		display: flex;
		justify-content: space-between;
	}

	.record-distance {
		color: #4CAF50;
	}
</style>